package web.suzy.oj.manager.file;

import com.alibaba.excel.EasyExcel;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import web.suzy.oj.pojo.vo.ExcelUserVO;
import web.suzy.oj.utils.RedisUtils;

import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.net.URLEncoder;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;

/**
 * YangSuzy 软件工作室
 * 类名: UserFileManager
 * 描述: ---- 待定 -----
 * 功能: ---- 待定 -----
 *
 * @author YangSuzy
 * Date: 2022/11/28 13:39
 */
@Component
@Slf4j(topic = "suzyoj")
public class UserFileManager {
    @Autowired
    private RedisUtils redisUtils;

    /**
     * 方法名: generateUserExcel
     * 描述: 生成用户信息Excel表
     *
     * @param key      缓存 Key
     * @param response 响应
     * @return void
     * @date 2022/11/28 13:40
     * @auther YangSuzy
     **/
    public void generateUserExcel(String key, HttpServletResponse response) throws IOException {
        //设置响应格式为excel
        response.setContentType("application/vnd.ms-excel");
        response.setCharacterEncoding("utf-8");
        //这里URLEncoder.encode可以防止中文乱码
        String fileName = URLEncoder.encode(key, "UTF-8");
        //设置下载文件的文件名和格式
        response.setHeader("Content-disposition", "attachment;filename=" + fileName + ".xlsx");
        response.setHeader("Content-Type", "application/xlsx");
        //写入数据
        EasyExcel.write(response.getOutputStream(), ExcelUserVO.class)
                .sheet("用户数据")
                .doWrite(getGenerateUsers(key));
    }

    /**
     * 方法名: getGenerateUsers
     * 描述: 从缓存中获取生成的用户信息
     *
     * @param key 缓存 Key
     * @return java.util.List<web.suzy.oj.pojo.vo.ExcelUserVO>
     * @date 2022/11/28 13:46
     * @auther YangSuzy
     **/
    private List<ExcelUserVO> getGenerateUsers(String key) {
        List<ExcelUserVO> users = new LinkedList<>();
        Map<Object, Object> userInfo = redisUtils.hmget(key);
        for (Object hashKey : userInfo.keySet()) {
            String username = (String) hashKey;
            String password = (String) userInfo.get(hashKey);
            users.add(new ExcelUserVO().setUsername(username).setPassword(password));
        }
        return users;
    }
}
